define(['config', 'text!app/module/system/departField.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate','ztree', 'ztreecheck',
    'css!app/assets/lib/ztree/css/demo.css',
    'css!app/assets/lib/ztree/css/zTreeStyle/zTreeStyle.css'
], function (config, viewHTML, laypage,
    mydialog, autocomplete, jqGrid, common, laydate) {

    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_url = "/api/depart/search";

    var model = avalon.define({
        $id: "departField",
        employeeInfo: {},
        // 查询条件
        query: {
            departName: "",
            departId: ""
        },
        init: function () {
            model.loadGrid();
            model.addEvent();
        },
        loadGrid: function () {
            var i = Public.setGrid();
            $("#grid").jqGrid({
                loadBeforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader("X-AuthToken", token);
                },
                datatype: "json",
                mtype: "GET",
                url: grid_url,
                postData: model.query.$model,
                loadComplete: function (data) {},
                loadError: function (xhr, status, error) {
                    alert(JSON.parse(xhr.responseText).msg);
                },
                colModel: [
                    {
                        name: "departID",
                        label: "组织ID",
                        width: '60'
                    },
                    {
                        name: "departCD",
                        label: "编号",
                        width: '80',
                    },
                    {
                        name: "departName",
                        label: "机构名称",
                        width: '150',
                    },
                    {
                        name: "memo_TX",
                        label: "机构简称",
                        width: "100"
                    },
                    {
                        name: "manager",
                        label: "权限管理",
                        align: "center",
                        width: '80',
                        title: false,
                        formatter: function (val, opt, row) {
                            return '<div class="manage" data-id="' + row.id + '"><a class="rightsManage"   href="javascript:void(0)"><span>权限设置</span></a></div>'
                        }
                    }
                ],
                cmTemplate: {
                    sortable: false,
                    title: false,
                    align: "center"
                },
                page: 1,
                rowNum: 10,
                rowList: [10, 20, 30],
                height: i.h,
                autowidth: true,
                pager: '#page',
                sortname: 'id',
                viewrecords: true,
                forceFit: false,
                rownumbers: true,
                // multiselect: true,
                multiboxonly: true,
                sortorder: "desc",
                jsonReader: {
                    root: "data.list",
                    records: "data.totalRow",
                    total: "data.totalPage",
                    repeatitems: false,
                    id: "id"
                },
                loadError: function () {
                    parent.Public.tips({
                        type: 1,
                        content: "加载数据异常！"
                    })
                }
            })
        },
        reset: function () {
            model.query = {
                departId: "",
                departName: ""
            };
            model.queryData();
        },
        queryData: function () {
            $("#grid").jqGrid("setGridParam", {
                url: grid_url,
                datatype: "json",
                mtype: 'GET',
                postData: model.query.$model
            }).trigger("reloadGrid");
        },
        //设置权限
        editRights: function (departId) {
            //发送ajax
            $.ajax({
                type: "POST",
                url: "/api/departField/getFields?departId="+departId,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-AuthToken", token);
                },
                success: function (data, status, xhr) {
                    //加载权限树
                    model.loadZtree(data);
                    dialog({
                        title: '权限设置',
                        content: $("#editRights"),
                        okValue: "确定",
                        ok: function () {
                            var s = model.submitCheckedNodes();
                            debugger;
                            $.ajax({
                                type: "POST",
                                url: "/api/departField/save?fields=" + s + "&departId=" + departId,
                                beforeSend: function (xhr) {
                                    xhr.setRequestHeader("X-AuthToken", token);
                                },
                                success: function (data, status, xhr) {
                                    debugger;
                                    if (data.success) {
                                        successDialog().showModal();
                                    } else {
                                        errorDialog().showModal();
                                    }
                                },
                                error: function() {
                                    errorDialog().showModal();
                                }
                            })
                        },
                        cancelValue: "取消",
                        cancel: function () {}
                    }).showModal();
                },
                error: function (responseData, textStatus, errorThrown) {
                    alert("Failed: " +
                        responseData);
                }

            });
        },
        //加载 权限树
        loadZtree: function (zNodes) {
            var zTreeObj;
            var setting = {
                check: {
                    enable: true
                },
                view: {
                    showTitle: true,
                    showIcon: true,
                    showLine: true,
                },
                data: {
                    simpleData: {
                        enable: true,
                    }
                }
            };
            zTreeObj = $.fn.zTree.init($('#treeDemo'), setting, zNodes);

        },
        //取得Ztree选中的结点 id即权限ID
        submitCheckedNodes: function () {
            var nodes = new Array();
            var zTreeObj = $.fn.zTree.getZTreeObj("treeDemo");
            nodes = zTreeObj.getCheckedNodes(true);
            var str = "";
            for (i = 0; i < nodes.length; i++) {
                if (str != "") {
                    str += ",";
                }
                str += nodes[i].name;
            }
            return str;
        },
        addEvent: function () {
            $("#search").click(function (e) {
                e.preventDefault();
                model.queryData();
            });
            $(".fa-refresh").click(function (e) {
                e.preventDefault();
                model.reset();
                model.queryData();
            })
            //编辑用户信息
            $(".grid-wrap").on("click", ".rightsManage", function (e) {
                var id = $("#grid").jqGrid('getGridParam', 'selrow'),
                    departId = $("#grid").jqGrid("getRowData", id).departID;
                model.editRights(departId);
            })
            
        },
        
    });

    function errorDialog(data) {
        var mydialog = dialog({
            title: "错误",
            content: "操作失败！",
            okValue: "确定",
            ok: function() {}
        });
        return mydialog;
    }

    function successDialog() {
        var mydialog = dialog({
            title: "成功",
            content: "操作成功！",
            okValue: "确定",
            ok: function() {}
        });
        return mydialog;
    }

    require(['jquery', 'domReady!'], function ($) {});

    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {} // 切换菜单时销毁原来的view
    };
    return viewmod;
});